package com.pure.common.optional;

import com.oracle.javafx.jmx.json.JSONFactory;
import jdk.nashorn.internal.parser.JSONParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.jackson.JsonComponent;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * @description: optional test
 * @date: 2022-06-01 13:57
 * @since 1.2.0
 **/
@Slf4j
public class OptionalTest {

    public static void main(String[] args) {

//        List<String> strings = Arrays.asList("oms/asd.jpeg-12121212121");
//        List<String> strings = Arrays.asList();
//        List<String> strings = Arrays.asList("oms/asd.jpeg-12121212121", "oms/asd.jpeg-1242421212121");
//        log.info(listOfString(strings));
        ofElse();
    }

    public static String listOfString(Object obj) {
        List<String> objects = (List<String>) obj;
        StringBuilder sb = new StringBuilder("[");
        for (Object o : objects) {
            sb.append("\"").append(o.toString()).append("\",");
        }
        if (sb.lastIndexOf(",") > 0) {
            sb = new StringBuilder(sb.substring(0, sb.lastIndexOf(",")));
        }
        sb.append("]");
        return sb.toString();
    }

    /**
     * @description: orElse(T other) 返回值如果存在，否则返回 other
     * @date 2022/6/1 2:23 下午
     * @since 1.2.1
     */
    public static void ofElse() {

        String nullName = null;
        String name = Optional.ofNullable(nullName).orElse("infinite");
        log.info("of else {}", name);

        String nameStr = "yun.li";
        String nullableName = Optional.ofNullable(nameStr).orElse("infinite");
        log.info("of else {}", nullableName);

        List<String> names = Arrays.asList("001", "002", "", "003", "", "004");
        Optional<List<String>> namesOpt = Optional.ofNullable(names);
        Integer size = namesOpt.map(List::size).orElse(0);
        log.info("optional size is {}", size);

        if (Optional.ofNullable(names).isPresent()) {
            log.info("names is size {}", names.size());
        }

        List<String> zeros = Arrays.asList();
        if (Optional.ofNullable(zeros).isPresent()) {
            log.info("zeros is size {}", zeros.size());
        }
    }

    /**
     * @description: 返回 true 如果存在值，否则为 false.
     * @date 2022/6/1 2:08 下午
     * @since 1.2.1
     */
    public static void isPresent() {

        // ofNullable 避免空指针异常
        String str2 = "infinite";
        log.info("str is present {}", Optional.ofNullable(str2).isPresent());

        String str1 = "";
        log.info("str is present {}", Optional.ofNullable(str1).isPresent());

        String str = null;
        log.info("str is present {}", Optional.ofNullable(str).isPresent());
    }

}
